package cn.itcast.servlet;

import cn.itcast.domain.Town;
import cn.itcast.service.impl.TownServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/TownServlet")
public class TownServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
        try {
            //获取表单数据
            String key = request.getParameter("key");

            //调用Servlet
            List<Town> towns = new TownServiceImpl().findByName(key);
            //把Java对象变成JSON格式的字符串
            String json = new ObjectMapper().writeValueAsString(towns);
            //把数据写个浏览器
            response.getWriter().println(json);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}